import http from 'api@/index'
import { ref, onMounted, nextTick } from 'vue'
import { msgWarning } from 'lib@/utils/el-utils'
import { SYSTEM_CODE_ENUM } from '@/config/enums/system'
/**
 * get方法，对应get请求
 * @param {String} urlName [请求的url地址名称 对应interface中定义的key值]
 * @param {Object} params [请求时携带的参数，必须是vue响应式数据 例子 params = reactive{name: 'chenxy8'}]
 * @param {Object} options [额外参数，requestMethod：请求方法。isAutoGetData：调用是否自动获取列表]
 */
export default function pageChangeControl(
  urlName,
  params,
  options,
) {
  let defaultOptions = {
    requestMethod: 'get',
    isAutoGetData: true
  }
  options = Object.assign(defaultOptions,options)
  const pageNum = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const tableLoading = ref(false)
  let tableData = ref([])
  // 获取参数
  function getData() {
    let newObj = {}
    // 去掉搜索参数两端空格
    for (const key in params) {
      if (Object.hasOwnProperty.call(params, key)) {
        const val = params[key]
        // 去掉空值参数
        if ((typeof val === 'string') && (!!val || val === 0)) {
          newObj[key] = val.trim()
        }
        if(Object.prototype.toString.call(val) === '[object Array]'&&val.length>0){
          newObj[key] = val
        }
        if(Object.prototype.toString.call(val) ==='[object Object]'&&Object.keys(val).length>0){
          newObj[key] = val
        }
      }
    }
    let sendData = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...newObj
    }
    tableLoading.value = true
    http[options.requestMethod](urlName, sendData)
      .then(res => {
        console.log(res, 'res')
        if (res.code === SYSTEM_CODE_ENUM.SUCCESS) {
          const data = res.data
          tableData.value.length = 0
          nextTick(() => {
            tableData.value = data.records
          })
          if(data.current){
            pageNum.value = data.current || 1
          }
          
          total.value = data.total || 0
        } else {
          msgWarning(res.message || 'error')
        }
      })
      .finally(() => {
        tableLoading.value = false
      })
  }
  // pageNum 变换
  function handleCurrentChange(val) {
    pageNum.value = val
    getData()
  }
  // pageSize变化
  function handleSizeChange(val) {
    pageNum.value = 1
    pageSize.value = val
    getData()
  }
  // 查询数据
  function searchData() {
    pageNum.value = 1
    getData()
  }
  // 刷新数据
  function refreshData() {
    getData()
  }
  onMounted(() => {
    if (options.isAutoGetData) {
      searchData()
    }
  })
  return {
    pageNum,
    pageSize,
    tableData,
    total,
    tableLoading,
    handleSizeChange,
    handleCurrentChange,
    searchData,
    refreshData
  }
}
